
function initChat (uid,onConnect,onMessage) {
  getOpenId(uid, function(fromuid){
    connectSocket();                  //连接socket
    onSocketError();                  //连接重试
    onSocketClose();                  //关闭socket
    onSocketOpen(fromuid, onConnect); //监听连接成功
    onSocketMessage(onMessage);       //接收新消息         
  });
}

function connectSocket(){
  let app = getApp();
  wx.connectSocket({
    url: app.globalData.socketUrl,
    success: function (res) {
      console.log('WebSocket 连接成功', res);
    },
    fail: function (res) {
      console.log('WebSocket 连接失败', res);
    }
  })
}

function onSocketOpen(fromuid,callback){
  let datas = { "type": "connect", "from_uid": fromuid };
      wx.sendSocketMessage({
        data: JSON.stringify(datas),
        success: function (res) {
          console.log('发送成功', res);
          callback();
        }, fail: function (err) {
          console.log('发送失败', err);
        }
      })
      //that.data.socketState = 'open';
}

function onSocketMessage(callback){
  wx.onSocketMessage(message => {
    //把JSONStr转为JSON
    message = message.data.replace(" ", "");
    if (typeof message != 'object') {
      message = message.replace(/\ufeff/g, ""); //重点
      var jj = JSON.parse(message);
      message = jj;
      if (message.type == 'send' && message.content) {
        callback(message);
        // that.setData({
        //   msgLength: 1
        // })
      }
    }
  })
}

function onSocketError(){
  let app = getApp();
  let reCount = 0;
  wx.onSocketError(function (err) {
    console.log('WebSocket 错误', err);
    reCount ++;
    if(reCount <= 3){
      connectSocket();
      // wx.connectSocket({
      //   url: app.globalData.socketUrl,
      //   success: function (res) {
      //     console.log('WebSocket 重连', res);
      //   },
      //   fail: function (err) {
      //     console.log('WebSocket 重连失败', err);
      //   }
      // })
    }              
  });
}

function onSocketClose(){
  wx.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！', res)
  });
}

function getOpenId(uid,callback){
  let app = getApp();
  wx.request({
    url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + uid,
    success: function (res) {
      if (res.data.Code == 0) {
        if(res.data.Data){
          callback(res.data.Data.Id);
        }        
      } else {
        wx.showModal({
          title: '提示',
          content: res.data.Message,
          showCancel: false
        })
      }
    }
  })
}

module.exports = {
  initChat: initChat
}